package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    //过滤器执行的逻辑
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取相应对象
        ServerHttpResponse response = exchange.getResponse();
        //从请求对象中获取请求路径
        String path = request.getURI().getPath();

        //直接判断地址中是否包含"login"
        if (path.contains("/login")) {
            // 如果包含,直接放行
            return chain.filter(exchange);
        }
        //从请求对象中获取请求头
        String token = request.getHeaders().getFirst("token");
        //没有token，返回401
        if (StringUtils.isEmpty(token)) {
            //设置返回状态
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接相应给客户端,不在往后端发送请求转发
            return response.setComplete();
        }
        try {
            //如果有token,验证token是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claimsBody);
            //有效
            if (result== -1 ||result ==0){
                Object userId = claimsBody.get("userId");
                //将用户id放回到请求头中，然后将带有用户id的请求转发给后端的微服务，放行请求
                request.mutate().header("userId",userId.toString());
                return chain.filter(exchange);
            }
        }catch (Exception e){
            //记录日志
            log.error(e.getMessage());
        }
        //设置状态码 401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //直接相应给客户端,不在往后端发送请求转发
        return response.setComplete();
    }

    //过滤器执行的顺序 数值越小,优先级越高
    public int getOrder() {
        return 0;
    }
}
